package com.zs4sdk.activity;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zs4sdk.Zs4GameBase;
import com.zs4sdk.activity.login.Zs4GameLoginActivity;
import com.zs4sdk.activity.resetPassword.Zs4GameResetPasswordActivity;
import com.zs4sdk.dialog.IdCardInfoDialog;
import com.zs4sdk.dialog.VerifyIdCardDialog;
import com.zs4sdk.Zs4GameMenu;
import com.zs4sdk.common.Extra;
import com.common.library.data.CommonEventHandler.ResultHandlerInEvent;
import com.common.library.data.CommonHandle;
import com.common.library.data.CommonHandle.HandleMessage;
import com.common.library.data.EventHandler2Get;
import com.zs4sdk.entity.VerifyIdCardInfoEntity;
import com.zs4sdk.entity.Zs4GameData;
import com.zs4sdk.entity.PersonInfoEntity;
import com.common.library.listener.OnProcessListener;
import com.common.library.util.ActivityHelper;
import com.common.library.util.Helper;
import com.common.library.util.ParamsHelper;

/**
 * function: 账号中心
 *
 * @ author: aXiBa
 */
public class Zs4GameAcountCenterActivityBase extends Zs4GameBaseActivity implements View.OnClickListener {

    public static final String TAG = Zs4GameAcountCenterActivityBase.class.getSimpleName();
    protected final String mRedColor = "#FC8114";
    protected final String mBlackColor = "#909090";
    protected final int CAN_MODIFY_NICKNAME = 1;
    protected String backSendMsg = Extra.BOOLEAN_FALSE;
    protected TextView mTxvNickname;
    protected RelativeLayout mRelSafePhone;
    protected TextView mTxvPhoneBind;
    protected RelativeLayout mRelIdVerifyLoyout;

    protected TextView isVerifyIdcard;
    /**
     * 是否绑定邮箱、手机
     */
    protected String mBindPhone;
    CommonHandle myHandle = new CommonHandle(Zs4GameAcountCenterActivityBase.this, new HandleMessage() {

        @Override
        public void doHandleMessage(Message msg) {

            if (Extra.MessageKey.PERSON_INFO_SUCCESS == msg.what) {
                JSONObject result = (JSONObject) msg.obj;
                dePersonInfoSuccess(msg);
            }else if(Extra.MessageKey.REQUEST_VERIFY_SUCCESS == msg.what){
                VerifyIdCardInfoEntity entity = new VerifyIdCardInfoEntity((JSONObject) msg.obj);
                if(entity.isSuccess()){
                    new IdCardInfoDialog(Zs4GameAcountCenterActivityBase.this, entity.getName(),entity.getId_number()).show();
                }else {
                    ActivityHelper.showToast(entity.getDesc());
                }
                mRelIdVerifyLoyout.setEnabled(true);
            }
        }
    });

    protected  void dePersonInfoSuccess(Message msg){
        PersonInfoEntity personInfoEntity = new PersonInfoEntity((JSONObject) msg.obj);
        if (personInfoEntity.isSuccess()) {

            mTxvNickname.setText("用户名："+ personInfoEntity.getNickname());
//                    NnbTextView.setText(personInfoEntity.getNnb()+"平台币");

            //手机是否绑定
            if (Helper.isEmpty(personInfoEntity.getMobile())) {
                mTxvPhoneBind.setText(ActivityHelper.getStringResId("zs4gamestring_account_ensure_update"));
                mTxvPhoneBind.setTextColor(Color.parseColor(mRedColor));
                mRelSafePhone.setClickable(true);

            } else {
//                        mTxvNickname.setText("用户名："+ personInfoEntity.getMobile());
                mBindPhone = personInfoEntity.getMobile();
                mTxvPhoneBind.setText(ActivityHelper.setPhone(mBindPhone));
                mRelSafePhone.setClickable(false);
                mTxvPhoneBind.setTextColor(Color.parseColor(mBlackColor));
            }

        } else {
            mRelSafePhone.setClickable(false);
            //获取个人信息失败
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(ActivityHelper.getLayoutResId("zs4gamelayout_act_accountcenter_menu"));

        getParams();

        init();
    }

    @Override
    protected void init() {
        super.init();

        setTopTitle(ActivityHelper.getStringResId("zs4gamestring_title_accountenter"));

        initReferences();

        // 账号列表
        initAccountList();

        setViewClickEvent(this, ActivityHelper.getIdResId("zs4gameviewid_mNicknameUpdateView_act_accountcenter_menu"));

        requestPersonInfo();
    }

    /**
     * 请求个人信息
     */
    private void requestPersonInfo() {

        new EventHandler2Get(
                Extra.URL.PERSON_INFO,
                ParamsHelper.getUserAgent1(),
                new ResultHandlerInEvent() {

                    @Override
                    public void doResultHanler(JSONObject result) throws JSONException {
                        Message msg = myHandle.obtainMessage();

                        msg.what = Extra.MessageKey.PERSON_INFO_SUCCESS;
                        msg.obj = result;

                        // 发送消息
                        myHandle.sendMessage(msg);
                    }

                    @Override
                    public void doExceptionHandler() {

                    }
                });
    }

    // 初始化操作列表
    private void initAccountList() {
        mTxvNickname.setText(Zs4GameData.getInstance().getNickName());
        if(Zs4GameData.getInstance().isVerify()){
            isVerifyIdcard.setText(ActivityHelper.getStringResId("zs4gamestring_account_start_verify_id_success"));
        }else {
            isVerifyIdcard.setText(ActivityHelper.getStringResId("zs4gamestring_account_start_verify_id_now"));
        }
    }

    // 到登录
    private void goLoginActivity() {
        Bundle bundle = new Bundle();
        bundle.putInt(Extra.INTENTKEY.SCREEN_ORIENTATION, this.mScreenOrientation);
        bundle.putString(Extra.INTENTKEY.FLAG, flag);
        bundle.putString(Extra.INTENTKEY.BACKSENDMESSAGE, Extra.BOOLEAN_TRUE);
        bundle.putString(Extra.INTENTKEY.FROMACTIVITY, TAG);
        Intent intent = new Intent(this, Zs4GameLoginActivity.class);
        intent.putExtras(bundle);
        startActivityForResult(intent, Extra.REQUESTCODE.REQUESTLogin);
    }

    // 到修改密码
    protected void goChangePasswordActivity() {
        Intent intent = new Intent(this, Zs4GameChangePasswordActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt(Extra.INTENTKEY.SCREEN_ORIENTATION, this.mScreenOrientation);
        bundle.putString(Extra.INTENTKEY.FLAG, flag);
        intent.putExtras(bundle);
        startActivityForResult(intent, Extra.REQUESTCODE.CHAGEPASSWORD);
    }


    // 到绑定安全手机
    protected void goBindSafePhone() {
        //Zs4GameBindSafeAccountActivity
        Intent intent = new Intent(this, Zs4GameBindSafePhoneActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt(Extra.INTENTKEY.SCREEN_ORIENTATION, this.mScreenOrientation);
        bundle.putString(Extra.INTENTKEY.FLAG, flag);
        bundle.putInt(Extra.INTENTKEY.BIND_PHONE,Extra.REQUESTCODE.REQUEST_BIND_PHONE);
        intent.putExtras(bundle);
        startActivityForResult(intent, Extra.REQUESTCODE.REQUEST_BIND_PHONE);

    }

    /**
     * 消费记录
     */
    private void goPayRecord() {
        Zs4GameMenu.showWebView(this, getString(ActivityHelper.getStringResId("zs4gamestring_text_payrecord")), Extra.URL.PAYRECORDURL, "", "");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

//        // 修改密码后更新账号信息
//        if (requestCode == Extra.REQUESTCODE.CHAGEPASSWORD && resultCode == Extra.RESULTCODE.SUCCESS) {
//
//        }
//        //绑定手机成功
//        if (requestCode == Extra.REQUESTCODE.REQUEST_BIND_PHONE && resultCode == Extra.RESULTCODE.RESULT_BIND_PHONE) {
//            if (Helper.isNotNull(data)) {
//                //手机号
//                String phone = data.getStringExtra(Extra.INTENTKEY.BIND_PHONE);
//                if (Helper.isNotNull(phone)) {
//                    mTxvPhoneBind.setText(ActivityHelper.setPhone(phone));
//                    //重置
//                    mBindPhone = phone;
//                    mTxvNickname.setText(Zs4GameData.getInstance().getNickName());
//                }
//            }
//        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        requestPersonInfo();
    }

    /**
     * function: 初始化引用
     *
     * @ author: aXiBa 2013-3-20 下午2:15:02
     */
    private void initReferences() {

        mTxvNickname = findView(TextView.class, ActivityHelper.getIdResId("zs4gameviewid_txv_nickname"));

        mRelSafePhone = findView(RelativeLayout.class, ActivityHelper.getIdResId("zs4gameviewid_rel_safe_phone"));

        mRelIdVerifyLoyout = findView(RelativeLayout.class, ActivityHelper.getIdResId("zs4gameviewid_rel_idcard_verify"));

        mTxvPhoneBind = findView(TextView.class, ActivityHelper.getIdResId("zs4gameviewid_txv_safe_phone_bind"));
        isVerifyIdcard = findView(TextView.class, ActivityHelper.getIdResId("zs4gameviewid_txv_idcard_verify_tip"));
        checkGuest();
        setViewClickEvent(this, ActivityHelper.getIdResId("zs4gameviewid_rel_change_password"),//修改密码
                ActivityHelper.getIdResId("zs4gameviewid_rel_safe_phone"),//绑定手机
                ActivityHelper.getIdResId("zs4gameviewid_rel_payrecord"),//充值记录
                ActivityHelper.getIdResId("zs4gameviewid_rel_idcard_verify"),//身份认证
                ActivityHelper.getIdResId("zs4gameviewid_lin_rebind_phone"),//安全手机重新绑定
                ActivityHelper.getIdResId("zs4gameviewid_do_logout"));//注销

    }

    protected void checkGuest(){
        if (Zs4GameData.getInstance().isGuest()){
            mRelSafePhone.setEnabled(true);
            View view = findView(RelativeLayout.class,ActivityHelper.getIdResId("zs4gameviewid_lin_change_password"));
            view.setVisibility(View.GONE);
            mTxvPhoneBind.setText(ActivityHelper.getStringResId("zs4gamestring_account_ensure_update"));
        }else {
            mRelSafePhone.setEnabled(false);

        }
    }
    @Override
    protected void onResume() {
        super.onResume();
    }


    /**
     * 请求身份认证信息
     */
    private void requestIdCardInfo() {
        mRelIdVerifyLoyout.setEnabled(false);
        new EventHandler2Get(
                Extra.URL.GET_ID_CARD,
                ParamsHelper.getUserAgent1(),
                new ResultHandlerInEvent() {

                    @Override
                    public void doResultHanler(JSONObject result) throws JSONException {
                        Message msg = myHandle.obtainMessage();

                        msg.what = Extra.MessageKey.REQUEST_VERIFY_SUCCESS;
                        msg.obj = result;

                        // 发送消息
                        myHandle.sendMessage(msg);
                    }

                    @Override
                    public void doExceptionHandler() {
                        mRelIdVerifyLoyout.setEnabled(true);
                    }
                });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int id = v.getId();
        if (ActivityHelper.getIdResId("zs4gameviewid_rel_change_password") == id) {
            //修改密码
            goChangePasswordActivity();
        } else if (ActivityHelper.getIdResId("zs4gameviewid_rel_safe_phone") == id) {
            //绑定手机
            goBindSafePhone();
        } else if (ActivityHelper.getIdResId("zs4gameviewid_rel_payrecord") == id) {
            //消费记录
            goPayRecord();
        } else if (ActivityHelper.getIdResId("zs4gameviewid_rel_idcard_verify") == id) {
            //身份认证
            //去认证页面
            if(Zs4GameData.getInstance().isVerify()){
                requestIdCardInfo();
            }else {
                new VerifyIdCardDialog(this, false, new VerifyIdCardDialog.VerifyIdCardDialogLoginListener() {
                    @Override
                    public void onClick(boolean isverify) {
                        if(isverify){
                            initAccountList();
                        }
                    }
                }).show();
            }
        }
        else if (ActivityHelper.getIdResId("zs4gameviewid_do_logout") == id) {
            // sdk账号注销
            Zs4GameBase.getInstance().logout(this, new OnProcessListener() {

                @Override
                public void finishProcess(int code, Bundle bundle) {
                }
            });
        }else if(ActivityHelper.getIdResId("zs4gameviewid_lin_rebind_phone") == id){
            goCheckPhone();
        }
    }


    protected void goCheckPhone(){
        Class<?> cls =  Zs4GamePhoneCheckActivity.class;
        Intent intent = new Intent(this, cls);
        intent.putExtra("phone",mBindPhone);
        intent.putExtra("classStyle",2);
        startActivity(intent);
    }
    @Override
   protected   int getLeftBtnType() {

        if (Extra.FLAG_MENU.equals(flag) || Extra.FLAG_MANUAL_MENU.equals(flag)) {
            return TYPE_LEFTBTN_BACKTOMENU;
        } else if (Extra.BOOLEAN_TRUE.equals(backSendMsg)|| Extra.FLAG_MENU_ACCOUNT.equals(flag)||getPackageName().concat(Extra.ACTIONKEY.CLOSEACTIVITY_POSTFIX_MENU).equals(flag)) {
            return TYPE_LEFTBTN_BACKTOGAME;
        } else {
            return TYPE_LEFTBTN_BACK;
        }
    }
    @Override
    protected int getRightBtnType() {
        return TYPE_RIGHTBTN_INVISIBLE;
    }

    private void getParams() {

        Intent intent = this.getIntent();

        if (Helper.isNotNull(intent)) {

            if (intent.hasExtra(Extra.INTENTKEY.BACKSENDMESSAGE)) {
                backSendMsg = intent.getStringExtra(Extra.INTENTKEY.BACKSENDMESSAGE);
            }

            Bundle bundle = intent.getExtras();
            if (Helper.isNotNull(bundle)) {
                if (Helper.isNotNull(bundle) && bundle.containsKey(Extra.INTENTKEY.BACKSENDMESSAGE)) {
                    backSendMsg = bundle.getString(Extra.INTENTKEY.BACKSENDMESSAGE);
                }
            }
        }
    }
}
